package com.flyduck.vueshop.product.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyduck.vueshop.product.entity.AppProduct;
import com.flyduck.vueshop.product.entity.AppSkuStock;
import com.flyduck.vueshop.product.mapper.AppProductMapper;
import com.flyduck.vueshop.product.mapper.AppSkuStockMapper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * AppSkuStockManager
 * </p>
 *
 * @author flyduck
 * @since 2024-05-20
 */
@Component
public class AppSkuStockManager {

    @Resource
    private AppSkuStockMapper appSkuStockMapper;
    @Resource
    private AppProductMapper appProductMapper;

    /**
     * 根据spuId获取商品所有的sku(规格、库存、价格)
     * 如果spuId在app_sku_stock存在，说明是多规格商品，返回app_sku_stock的所有记录
     * 如果spuId在app_sku_stock不存在，说明是单规格商品，将spu作为一个sku返回
     * @param productId
     * @return
     */
    public List<AppSkuStock> getAppSkuStockListByProductId(Long productId) {
        //多规格商品
        List<AppSkuStock> appSkuStockList = appSkuStockMapper.selectList(
                new LambdaQueryWrapper<AppSkuStock>()
                        .eq(AppSkuStock::getProductId, productId)
        );

        //单规格商品
        if (CollectionUtil.isEmpty(appSkuStockList)) {
            appSkuStockList = ListUtil.toList(getSingleSkuStock(productId));
        }
        return appSkuStockList;
    }

    /**
     * 获取单规格商品的属性、库存、价格，封装到AppSkuStock
     * 价格、库存：从product取
     * sku：写死为默认规格
     * id：写死为-1
     * @param productId
     * @return
     */
    public AppSkuStock getSingleSkuStock(Long productId) {
        AppProduct appProduct = appProductMapper.selectById(productId);

        AppSkuStock appSkuStock = new AppSkuStock();
        appSkuStock.setPrice(appProduct.getPrice());
        appSkuStock.setStock(appProduct.getStock());
        appSkuStock.setSku("默认规格");
        appSkuStock.setId(-1L);
        return appSkuStock;
    }
}
